package com.usb.serial.device.util;


import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.usb.serial.device.MainActivity;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;

/**
 * jjh
 */
public class ReadUtil {

    private static final String USB = "/dev/ttyUSB0";

    private static final String CODE = "38400";

    private String byteArrToHex  = "";

    private SerialControl serialControl;

    private static volatile ReadUtil readUtil = null;


    public static ReadUtil getReadUtil() {

        synchronized (ReadUtil.class) {
            if (readUtil == null) {
                readUtil = new ReadUtil();
            }
        }
        return readUtil;

    }

    public void init() {
        serialControl = new SerialControl();
        initRead();
    }

    class SerialControl extends SerialHelper {

        @Override
        protected void onDataReceived(final ComBean comBean) {

//            runOnUiThread(new Runnable() {
//                public void run() {
            Log.i(TAG, "DispRecData: ");
            DispRecData(comBean);
        }
//            });

    }

    StringBuilder sMsg;

    private String DispRecData(SerialHelper.ComBean ComRecData) {

        if (sMsg == null) {
            sMsg = new StringBuilder();
        }
        byte[] bytes = ComRecData.bytes;

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));  // 将每个字节转换为两位的十六进制字符串
        }
        String hexString = sb.toString();  // 获取十六进制字符串
        BigInteger decimal = new BigInteger(hexString, 16);  // 将十六进制字符串转换为十进制数值
//        sMsg.setLength(0);
//        sMsg.append(byteArrToHex);
        byteArrToHex = String.valueOf(decimal);

        return byteArrToHex;


    }

    private void initRead() {


        serialControl.setPort(USB);
        serialControl.setBaudRate(CODE);
        File file =new File(USB);
        try {
            serialControl.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!file.canRead() || !file.canWrite()) {
//            Toast.makeText(MainActivity.this,"/dev/ttyUSB0" +"：：无权限",Toast.LENGTH_SHORT).show();
            return;
        }

    }

}




